<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('TT.WarmSet.Title') }}</view>
      </HeaderLayout>
    </template>

    <view class="container">
      <PageTitle
        :title="$t('TT.WarmSet.Temp.Lable')"
        :temp="curTemp"
        :page-hint="mode"
        :show-bar="(Number(curTemp) == 3276.7 && isMR120) || (Number(curTemp) == 120 && isMR100IRFEMS)"
      ></PageTitle>
      <view class="tab-box">
        <view class="tabs">
          <view class="tab" :class="{ active: curTab === 0 }" @click="chooseTab(0)">
            <view class="tab-text">{{ $t('TT.WarmSet.Tab.TempFire.Text') }}</view>
            <view class="tab-line"></view>
          </view>
          <view class="tab" :class="{ active: curTab === 1 }" @click="chooseTab(1)">
            <view class="tab-text">{{ $t('TT.WarmSet.Tab.TempSet.Text') }}</view>
            <view class="tab-line"></view>
          </view>
        </view>
      </view>
      <view v-show="curTab === 0">
        <view class="tab2">
          <view class="vTemp">
            <image src="@/pages/appliance/static/TT/img_fire1.png"></image>
          </view>
          <view class="auto-mode-des">{{ $t('TT.WarmSet.Tab.TempFire.Introduce.Text') }}</view>
          <view class="auto-mode-des">{{ $t('TT.WarmSet.Tab.TempFire.Introduce.Bottom.Text') }}</view>
        </view>
      </view>
      <view v-show="curTab === 1">
        <view class="tab1">
          <ChooseTemp
            :data="degrees"
            :cur-index="curIndex"
            :isUnit="true"
            :removeZero="true"
            @chooseTemp="chooseTemp"
            @pickState="changePickState"
          />
        </view>
      </view>
    </view>

    <template #footer>
      <FooterLayout :size="footerSize" :footer-style="footerStyle">
        <ActionButton :disabled="disabled || curType === newCurTab" @click="optionConfirm">{{
          $t('TT.WarmSet.Buttom.Button')
        }}</ActionButton>
      </FooterLayout>
    </template>

    <!-- EMS OTA升级弹框 -->
    <OtaUpgradeIRF :show="isMR100IRF || isMR100IRFEMS" :mcu-status="mcuStatus"></OtaUpgradeIRF>
  </PageLayout>
</template>
<script lang="ts">
export type SetSettingType = {
  settings: { key: string; value: string | number }[]
}
</script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import netconfig from '@/config/netconfig'
import FooterLayout from '@/layout/page/footer.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import PageTitle from '../components/pageTitle/pageTitle.vue'
import ChooseTemp from '../components/chooseTemp/chooseTemp.vue'
import OtaUpgradeIRF from '../otaUpgrade/otaUpgradeIRF.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import { actionDebounce, showLoading, useEventReceiver } from '@/utils/mpHelper'
import type { TTController } from '@/controller/TT/definition'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { setTTSetting } from '@/api/tt'
import {
  TT_SETTING_BLMODE,
  TT_SETTING_CHSET,
  TT_SETTING_MODE,
  TT_SUMMER_BLMODE,
  TT_SUMMER_MODE,
} from '@/constants/Command'
import { setTTBLMode, TT_SETTING_BlCHSet, TT_SETTING_BlState } from '../SmartAssistantTool'
import type { Remote } from '@/controller/base/types/remote'

const control = ref<TTController.Control | null>(null)
useEventReceiver('control', (received: TTController.Control) => {
  control.value = received
  listenMessages()
})

const headerStyle = {
  backgroundColor: '#fff',
}
const imgUrl = `${netconfig.ASSETSPRE_ICONS}`
const degrees = ref<{ value: number }[]>([])
for (let i = 40; i <= 88; i++) {
  degrees.value.push({
    value: i,
  })
}

const haId = ref('')
const isMR120 = computed(() => haId.value.indexOf('MR120') !== -1)
const isMR100IRF = computed(() => haId.value.split('-')[1] === 'MR100iRF10720')
const isMR100IRFEMS = computed(() => haId.value.split('-')[1] === 'MR100iRF10720EMS')

const newCurTab = computed(() => control.value?.store.curTab)
const curTemp = computed(() => (control.value?.store.warmTemp ? Number(control.value?.store.warmTemp) / 10 + '' : '0'))
const warmTempSetInt = computed(() => control.value?.store.warmTempSetInt)
const blState = computed(() => control.value?.store.blState)
const BlCHMAX = computed(() => control.value?.store.BlCHMAX)
const mcuStatus = computed(() => control.value?.store.mcuStatus || 0)

const mode = computed(() => (newCurTab.value === 0 ? '恒温控焰' : '温度设定'))
const curType = ref(-1)

const curTab = ref(0)
const curIndex = ref(0)
const tempIndex = ref(0)
const pickState = ref(false)
const disabled = ref(false)

watch(
  () => control.value?.store.curTab,
  (value) => {
    let newValue = Number(value) ? Number(value) : 0
    curTab.value = newValue
    curType.value = newValue
  },
  {
    immediate: true,
  }
)
watch(
  () => warmTempSetInt.value,
  (value) => {
    if (!value || degrees.value.length === 0) return
    degrees.value.forEach((item, index) => {
      if (item.value === Number(value)) {
        nextTick(() => {
          curIndex.value = index
          tempIndex.value = index
        })
      }
    })
  }
)
watch(
  () => BlCHMAX.value,
  (max) => {
    if (!max) return
    degrees.value = []
    for (let i = 40; i <= Number(max); i++) {
      degrees.value.push({
        value: i,
      })
    }
  }
)

onLoad((query: any) => {
  haId.value = query?.haId
})

onUnload(() => {
  control.value?.remote.removeBatchObserves(observes)
})

/**
 * 切换tab
 */
function chooseTab(index: number) {
  curTab.value = index
  disabled.value = false
  curType.value = -1
}
/**
 * 选择温度
 * @param index
 */
function chooseTemp(index: number) {
  curIndex.value = index
  disabled.value = false
  tempIndex.value = index
  curType.value = -1
}
/**
 * 滚动
 * @param state
 */
function changePickState(state: boolean) {
  pickState.value = state
}
/**
 * 点击确定
 */
const optionConfirm = actionDebounce({
  call: async () => {
    disabled.value = true
    if (curTab.value === 0) {
      setAuto()
    } else {
      setTemp()
    }
  },
})
/**
 * 设置温度
 */
function setTemp() {
  return showLoading(async () => {
    let params = {
      settings: [
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: TT_SETTING_CHSET,
          value: degrees.value[tempIndex.value].value,
        },
        {
          key: TT_SETTING_MODE,
          value: 1,
        },
      ],
    }
    if (isMR100IRF.value || isMR100IRFEMS.value) {
      params = {
        settings: [
          {
            key: TT_SETTING_BlState,
            value: setTTBLMode(blState.value as string, '1'),
          },
          {
            key: TT_SETTING_BlCHSet,
            value: degrees.value[tempIndex.value].value,
          },
        ],
      }
    } else if (isMR120.value) {
      params = {
        settings: [
          {
            key: TT_SETTING_BLMODE,
            value: curTab.value || 0,
          },
          {
            key: TT_SETTING_BlCHSet,
            value: degrees.value[tempIndex.value].value,
          },
        ],
      }
    }
    await setSetting(params)
  })
}
/**
 * 设置恒温控焰
 */
function setAuto() {
  return showLoading(async () => {
    let params = {
      settings: [
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: TT_SETTING_MODE,
          value: 0,
        },
      ],
    }
    if (isMR100IRF.value || isMR100IRFEMS.value) {
      params = {
        settings: [
          {
            key: TT_SETTING_BlState,
            value: setTTBLMode(blState.value as string, '0'),
          },
        ],
      }
    } else if (isMR120.value) {
      params = {
        settings: [
          {
            key: TT_SETTING_BLMODE,
            value: curTab.value || 0,
          },
        ],
      }
    }
    await setSetting(params)
  })
}
/**
 * 下发设置指令
 * @param params
 */
async function setSetting(params: SetSettingType) {
  const res = await setTTSetting(haId.value, params)
  uni.showToast({
    title: '设置成功',
    icon: 'none',
  })
}
/**
 * 监听
 */
const observes: Remote.BatchObserve<TTController.Store>[] = [
  {
    matcher: (msg) => [TT_SUMMER_MODE, TT_SUMMER_BLMODE].includes(msg.key),
    handler: (msg) => {
      if (Number(msg.value) === 1) {
        uni.navigateBack()
      }
    },
  },
]
function listenMessages() {
  control.value?.remote.addBatchObserves(observes)
}
</script>
<style scoped lang="less">
@import '@/styles/common.less';
.hidden {
  display: none;
}
.container {
  .tab-box {
    padding: 0 40rpx;
    width: 100%;
    height: 88rpx;
    box-sizing: border-box;
  }

  .tabs {
    margin-top: 32rpx;
    display: flex;
    width: 100%;
    height: 88rpx;
    align-items: stretch;
  }

  .tab {
    width: 50%;
    position: relative;
    flex-grow: 1;
    line-height: 88rpx;
    color: #808a96;
    text-align: center;
    &.active {
      .tab-text {
        color: var(--primary-color);
        opacity: 1;
      }
      .tab-line {
        background: var(--primary-color);
      }
    }
  }

  .en-tab-class {
    font-size: 32rpx;
    font-weight: 400;
  }
  .tab-text {
    font-weight: 500;
    font-size: 32rpx;
    color: var(--dark-color);
    opacity: 0.6;
  }

  .tab-line {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translate(-50%, 0);
    width: 68rpx;
    height: 4rpx;
    background-color: transparent;
  }

  .tab2 {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .tab1 {
    padding-top: 48rpx;
  }
  .vTemp {
    margin-top: 48rpx;
    font-size: 80rpx;
    color: #4475d5;
  }

  .vTemp image {
    width: 200rpx;
    height: 160rpx;
    margin-bottom: 32rpx;
  }

  .auto-mode-des {
    font-weight: 400;
    font-size: 32rpx;
    line-height: 44rpx;
    color: var(--dark-color);
  }
}
</style>
